<?php
/**
 * Created by PhpStorm.
 * User: HCDX
 * Date: 2018/7/20
 * Time: 14:35
 * by Hedy<714195347@qq.com>
 */
namespace App\Http\Controllers;

use App\Http\Requests\UserAddressRequest;
use App\Models\UserAddress;
use Illuminate\Http\Request;

class UserAddressesController extends Controller
{
    /**
     * 收货地址展示页面
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        //把当前用户下的所有地址作为变量$addresses注入到模板中
        return view('user_addresses.index',[
            'addresses'  =>  $request->user()->addresses,
        ]);
    }

    /**
     * 新增收货地址
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create()
    {
        return view('user_addresses.create_and_edit',[
            'address'=>new UserAddress()
        ]);
    }

    /**
     * 添加用户地址和数据的验证
     * $request->user()获取当前登录用户
     * user()->addresses()获取当前用户与地址的关系
     * addresses()->create()在关联关系里创建一个新的纪录
     * $request->only()通过白名单的方式从用户提交的数据里获取我们所需要的数据
     * @param UserAddressRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(UserAddressRequest $request)
    {
        $request->user()->addresses()->create($request->only([
            'province',
            'city',
            'district',
            'address',
            'zip',
            'contact_name',
            'contact_phone',
        ]));
        return redirect()->route('user_addresses.index');
    }

    /**
     * 编辑页面
     * @param UserAddress $user_address
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(UserAddress $user_address)
    {
        //添加限权
        $this->authorize('own',$user_address);
        return view('user_addresses.create_and_edit',['address'=>$user_address]);
    }

    /**
     * 保存更新数据库
     * @param UserAddress $user_address
     * @param UserAddressRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(UserAddress $user_address,UserAddressRequest $request)
    {
        //添加限权
        $this->authorize('own',$user_address);
        $user_address->update($request->only([
            'province',
            'city',
            'district',
            'address',
            'zip',
            'contact_name',
            'contact_phone',
        ]));
        return redirect()->route('user_addresses.index');
    }

    public function destroy(UserAddress $user_address)
    {
        //添加限权
        $this->authorize('own',$user_address);
        $user_address->delete();
//        return redirect()->route('user_addresses.index');
        //删除接口的请求方式从表单提交改成了 AJAX 请求，因此我们还需调整一下删除接口的返回值，否则 AJAX 请求会有异常：
        return [];
    }


}
